package com.yanwq.sayhi.base;

import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.yanwq.sayhi.R;

import butterknife.BindView;

/**
 * 作者：yanweiqiang。
 * 日期：2016/7/12 0012。
 */
public abstract class BaseToolbarActivity extends BaseActivity {
    @BindView(R.id.toolbar)
    public Toolbar mToolbar;

    private View mToolbarLayout;
    private int mToolbarLayoutHeight;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        setSupportActionBar(mToolbar);
        mToolbar.setNavigationIcon(R.drawable.ic_chevron_left_black_24dp);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    public void setContentView(@LayoutRes int layoutResID) {
        ViewGroup root = (ViewGroup) getWindow().getDecorView();
        View view = new View(this);
        view.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, getStatusBarHeight()));
        view.setBackgroundColor(getResources().getColor(R.color.blue));
        mToolbarLayout = LayoutInflater.from(this).inflate(R.layout.toolbar, root, false);
        View content = LayoutInflater.from(this).inflate(layoutResID, root, false);

        LinearLayout linearLayout = new LinearLayout(this);
        linearLayout.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        linearLayout.setOrientation(LinearLayout.VERTICAL);

        linearLayout.addView(view);
        linearLayout.addView(mToolbarLayout);
        linearLayout.addView(content);
        root.addView(linearLayout);

        root.post(new Runnable() {
            @Override
            public void run() {
                mToolbarLayoutHeight = mToolbarLayout.getMeasuredHeight();
            }
        });
    }

    public int getOriginToolbarLayoutHeight() {
        return mToolbarLayoutHeight;
    }

    public void setToolbarTopMargin(int topMargin) {
        if (topMargin > 0) {
            topMargin = 0;
        }

        if (topMargin < -mToolbarLayoutHeight) {
            topMargin = -mToolbarLayoutHeight;
        }

        ((FrameLayout.LayoutParams) mToolbarLayout.getLayoutParams()).topMargin = topMargin;
        mToolbarLayout.requestLayout();
    }

    public int getToolbarTopMargin() {
        return ((FrameLayout.LayoutParams) mToolbarLayout.getLayoutParams()).topMargin;
    }
}
